package com.mmd.base.hander;

import com.alibaba.fastjson.JSONObject;
import com.mmd.core.enums.ResultEnum;
import com.mmd.core.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 上下文中没有存储凭证时会调用该方法 具体请查看{@link com.mmd.base.hander.MyAuthFilter#doFilter()}中是否执行了UserContextHolder#setSecurityContextHolder()
        // 当用户访问所有非匿名访问的REST资源时而且不携带任何凭证时调用该方法
        log.info("未认证");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().print(JSONObject.toJSONString(Result.custom(ResultEnum.LOGIN)));
    }
}